package com.qut.graduate.busrtquery.fragment;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.qut.graduate.busrtquery.BRTQCache;
import com.qut.graduate.busrtquery.BRTQConstant;
import com.qut.graduate.busrtquery.R;
import com.qut.graduate.busrtquery.adapter.StationInfoAdapter;
import com.qut.graduate.busrtquery.adapter.StationQueryNearByAdapter;
import com.qut.graduate.busrtquery.adapter.StationQuerySuggestAdapter;
import com.qut.graduate.busrtquery.bean.User;
import com.qut.graduate.busrtquery.greendao.bean.BusLineCollect;
import com.qut.graduate.busrtquery.greendao.bean.StationInfo;
import com.qut.graduate.busrtquery.greendao.bean.StationInfoCollect;
import com.qut.graduate.busrtquery.greendao.controller.DBController;
import com.qut.graduate.busrtquery.interfaces.OnItemClickListener;
import com.qut.graduate.busrtquery.ui.MainActivity;
import com.qut.graduate.busrtquery.utils.common.LogUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

import cn.bmob.v3.BmobUser;

/**
 * @Author WLL
 * @Time: 2019/3/23 16:39
 */
public class StationQueryFragment extends BaseFragment {
    private static final String TAG = "StationQueryFragment";
    private LinearLayout mTopLayout;
    private LinearLayout mTabLayout;
    private EditText mSearchEditText;
    private Button mHistoryClearBtn;
    private LinearLayout mHistoryLayout;
    private TextView mCollectText;
    private LinearLayout mCollectLayout;
    private SwipeRefreshLayout mSuggestSwipeRefreshLayout;
    private RecyclerView mSuggestRecyclerView;
    private RecyclerView mHistoryRecyclerView;
    private RecyclerView mNearByRecyclerView;
    private RecyclerView mCollectRecyclerView;
    private PoiSearch mPoiSearch;
    private int loadIndex = 0;
    private List<Button> mButtonList = new ArrayList<>();
    private List<RecyclerView> recyclerViewList = new ArrayList<>();
    private StationQuerySuggestAdapter stationQuerySuggestAdapter;
    private StationQueryNearByAdapter stationQueryNearByAdapter;
    private StationInfoAdapter stationInfoHistoryAdapter;
    private StationInfoAdapter stationInfoCollectAdapter;
    private List<PoiInfo> mSuggestPoiInfoList = new ArrayList<>();
    private List<PoiInfo> mNearbyPoiInfoList = new ArrayList<>();
    private List<StationInfo> mStationInfoHistoryList = new ArrayList<>();
    private List<StationInfoCollect> mStationInfoCollectList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_station_query;
    }

    protected void init() {
        initView();
        initEvent();
    }

    private void initView() {
        mTopLayout = mRootView.findViewById(R.id.station_query_top_layout);
        LinearLayout mMainLayout = mRootView.findViewById(R.id.station_query_main_layout);
        mTabLayout = mRootView.findViewById(R.id.station_query_tab_layout);
        mSearchEditText = mRootView.findViewById(R.id.station_query_search_editText);
        Button mSuggestBtn = mRootView.findViewById(R.id.station_query_suggest_btn);
        Button mHistoryBtn = mRootView.findViewById(R.id.station_query_history_btn);
        Button mNearByBtn = mRootView.findViewById(R.id.station_query_nearby_btn);
        Button mCollectBtn = mRootView.findViewById(R.id.station_query_collection_btn);
        mHistoryClearBtn = mRootView.findViewById(R.id.station_query_history_clear_btn);
        mHistoryLayout = mRootView.findViewById(R.id.station_query_history_layout);
        mCollectText = mRootView.findViewById(R.id.station_query_collection_textView);
        mCollectLayout = mRootView.findViewById(R.id.station_query_collection_layout);
        mSuggestSwipeRefreshLayout = mRootView.findViewById(R.id.station_query_suggest_swipeRefreshLayout);
        mHistoryRecyclerView = mRootView.findViewById(R.id.station_query_history_recyclerView);
        mSuggestRecyclerView = mRootView.findViewById(R.id.station_query_suggest_recyclerView);
        mNearByRecyclerView = mRootView.findViewById(R.id.station_query_nearby_recyclerView);
        mCollectRecyclerView = mRootView.findViewById(R.id.station_query_collection_recyclerView);
        mButtonList.add(mSuggestBtn);
        mButtonList.add(mHistoryBtn);
        mButtonList.add(mNearByBtn);
        mButtonList.add(mCollectBtn);
        recyclerViewList.add(mSuggestRecyclerView);
        recyclerViewList.add(mHistoryRecyclerView);
        recyclerViewList.add(mNearByRecyclerView);
        recyclerViewList.add(mCollectRecyclerView);
        mSuggestBtn.setOnClickListener(this);
        mHistoryBtn.setOnClickListener(this);
        mNearByBtn.setOnClickListener(this);
        mCollectBtn.setOnClickListener(this);
        mHistoryClearBtn.setOnClickListener(this);
        mSuggestSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary); // 设置下拉进度的背景颜色，默认就是白色的
        mSuggestSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,
                R.color.colorPrimary, R.color.colorPrimaryDark); // 设置下拉进度的主题颜色
        mSuggestSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                BRTQCache.getInstance().setSQPoiSearchType(BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST_MORE);
                searchInNowCity(++loadIndex);
            }
        });
    }

    private void initEvent() {
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener((MainActivity) Objects.requireNonNull(getActivity()));
        changeNowRecyView(1);

        mSuggestRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        stationQuerySuggestAdapter = new StationQuerySuggestAdapter(getActivity(), mSuggestPoiInfoList);
        mSuggestRecyclerView.setAdapter(stationQuerySuggestAdapter);
        stationQuerySuggestAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                StationInfo stationInfo = new StationInfo(mSuggestPoiInfoList.get(position));
                ((MainActivity) getActivity()).gotoStationQuerySuccess(stationInfo);
                updateAllStationInfoData(stationInfo);
            }
        });

        mStationInfoHistoryList.addAll(BRTQCache.getInstance().getStationInfoHistoryList());
        mHistoryRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        stationInfoHistoryAdapter = new StationInfoAdapter(getActivity(), mStationInfoHistoryList,0);
        mHistoryRecyclerView.setAdapter(stationInfoHistoryAdapter);
        stationInfoHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                ((MainActivity) getActivity()).gotoStationQuerySuccess(mStationInfoHistoryList.get(position));
                mStationInfoHistoryList.get(position).setTime(BRTQConstant.timeFormat.format(System.currentTimeMillis()));
                updateAllStationInfoData(mStationInfoHistoryList.get(position));
                LogUtils.d("----StationQueryFragment  mStationInfoHistoryList.get(position):"
                        + mStationInfoHistoryList.get(position));
            }
        });
        setHistoryClearBtnVisibility();

        mStationInfoCollectList.addAll(BRTQCache.getInstance().getStationInfoCollectList());
        LogUtils.d("----StationQueryFragment  mStationInfoCollectList:" + mStationInfoCollectList, getClass());
        mCollectRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        stationInfoCollectAdapter = new StationInfoAdapter(getActivity(), mStationInfoCollectList,1);
        mCollectRecyclerView.setAdapter(stationInfoCollectAdapter);
        stationInfoCollectAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                StationInfo stationInfo = new StationInfo(mStationInfoCollectList.get(position));
                ((MainActivity) getActivity()).gotoStationQuerySuccess(stationInfo);
            }
        });

        mNearByRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        stationQueryNearByAdapter = new StationQueryNearByAdapter(getActivity(), mNearbyPoiInfoList);
        mNearByRecyclerView.setAdapter(stationQueryNearByAdapter);
        stationQueryNearByAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                StationInfo stationInfo = new StationInfo(mNearbyPoiInfoList.get(position));
                ((MainActivity) getActivity()).gotoStationQuerySuccess(stationInfo);
            }
        });

//        searchNearby(0); // 是进入界面就加载附近站点，还是每次点击附近站点按钮才请求附近的站点
        mSearchEditText.addTextChangedListener(new MyTextWatcher());
    }

    /**
     * 监听站点搜索顶部的searchEditText的内容改变
     */
    private class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (!mSearchEditText.getText().toString().trim().equals("")) {
                changeNowRecyView(0);
                BRTQCache.getInstance().setSQPoiSearchType(BRTQConstant.STATION_QUERY_POI_TYPE_SUGGEST);
                loadIndex = 0;
                searchInNowCity(loadIndex);
            } else {
                setRefreshStop();
                clearSuggestRecyView();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        updateStationInfoCollectRecyView();
        if (hidden) {
            changeNowRecyView(0);
            mSearchEditText.setText("");
        } else {
            updateStationInfoHistoryRecyView();
            if (getActivity() != null) {
                mTopLayout.setBackgroundColor(((MainActivity) getActivity()).getPrimaryColor());
                mTabLayout.setBackgroundColor(((MainActivity) getActivity()).getPrimaryColor());
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.station_query_suggest_btn:
                changeNowRecyView(0);
                break;
            case R.id.station_query_history_btn:
                changeNowRecyView(1);
                break;
            case R.id.station_query_nearby_btn:
                changeNowRecyView(2);
                searchNearby(0);
                break;
            case R.id.station_query_collection_btn:
                changeNowRecyView(3);
                break;
            case R.id.station_query_history_clear_btn:
                BRTQCache.getInstance().getStationInfoHistoryList().clear();
                updateStationInfoHistoryRecyView();
                DBController.getInstance().deleteAllTable(BRTQConstant.DB_TABLE_TYPE_STATION_INFO_HISTORY);
                break;
        }
    }

    /**
     * 搜索附近,sortType是一个排序规则，此处是由近到远的排序规则，
     * location 是一个坐标点，以这个坐标为中心;radius 是搜索半径，单位是m; pagenum 是搜索结果页数索引
     *
     * @param index
     */
    private void searchNearby(int index) {
        BRTQCache.getInstance().setSQPoiSearchType(BRTQConstant.STATION_QUERY_POI_TYPE_NEARBY);
        if (getActivity() != null) {
            LatLng mCurrentLatLng = ((MainActivity) getActivity()).getmCurrentLatLng();
            if (mCurrentLatLng != null) {
                PoiNearbySearchOption nearbySearchOption = new PoiNearbySearchOption().keyword("公交车站")
                        .sortType(PoiSortType.distance_from_near_to_far).location(mCurrentLatLng)
                        .radius(1000000000).pageCapacity(10).pageNum(index);
                mPoiSearch.searchNearby(nearbySearchOption);
            }
        }
    }

    /**
     * 在当前城市搜索指定公交车站点
     *
     * @param index
     */
    private void searchInNowCity(int index) {
        mSuggestSwipeRefreshLayout.setRefreshing(true);
        mPoiSearch.searchInCity((new PoiCitySearchOption()).city("青岛")
                .keyword(mSearchEditText.getText().toString()).pageNum(index));
    }

    /**
     * 点击  查询后的某个站点 或 站点查询历史中的某个站点  更新展示的站点历史的recyclerview、内存及数据库中的数据
     */
    public void updateAllStationInfoData(StationInfo stationInfo) {
        if (BRTQCache.getInstance().getStationInfoHistoryList() != null) {
            if (BRTQCache.getInstance().getStationInfoHistoryList().size() > 0) {
                for (int i = 0; i < BRTQCache.getInstance().getStationInfoHistoryList().size(); i++) {
                    if (BRTQCache.getInstance().getStationInfoHistoryList().get(i).getName().equals(stationInfo.getName())) {
                        BRTQCache.getInstance().getStationInfoHistoryList().get(i).setTime(stationInfo.getTime());
                        insertOrUpdateStationInfoHistoryTable(BRTQConstant.DB_STATION_INFO_HISTORY_UPDATE,
                                BRTQCache.getInstance().getStationInfoHistoryList().get(i));
                        break;
                    } else { // 站点名字不一样，即还没查询过该站点
                        if (i == BRTQCache.getInstance().getStationInfoHistoryList().size() - 1) {
                            BRTQCache.getInstance().getStationInfoHistoryList().add(stationInfo);
                            insertOrUpdateStationInfoHistoryTable(BRTQConstant.DB_STATION_INFO_HISTORY_INSERT,stationInfo);
                        }
                    }
                }
            }
            if (BRTQCache.getInstance().getStationInfoHistoryList().size() == 0) {
                BRTQCache.getInstance().getStationInfoHistoryList().add(stationInfo);
                insertOrUpdateStationInfoHistoryTable(BRTQConstant.DB_STATION_INFO_HISTORY_INSERT,stationInfo);
            }
            updateStationInfoHistoryRecyView();
        }
    }

    /**
     * 将站点的查询历史插入到数据库的表中
     */
    private void insertOrUpdateStationInfoHistoryTable(int type, StationInfo stationInfo) {
            if (type == BRTQConstant.DB_STATION_INFO_HISTORY_UPDATE)
                DBController.getInstance().updateTable(BRTQConstant.DB_TABLE_TYPE_STATION_INFO_HISTORY, stationInfo);
            if (type == BRTQConstant.DB_STATION_INFO_HISTORY_INSERT)
                DBController.getInstance().insertTable(BRTQConstant.DB_TABLE_TYPE_STATION_INFO_HISTORY, stationInfo);
    }

    /**
     * 停止SwipeRefreshLayout的加载进度条
     */
    public void setRefreshStop() {
        mSuggestSwipeRefreshLayout.setRefreshing(false);
    }

    /**
     * 第一次查询站点后，更新查询建议RecyView
     * @param poiInfos
     */
    public void firstRequestSuggestRecyView(List<PoiInfo> poiInfos) {
        mSuggestPoiInfoList.clear();
        updateSuggestRecyView(poiInfos);
    }

    /**
     * 再次对某个地点进行查询后，更新查询建议RecyView
     * @param poiInfos
     */
    public void updateSuggestRecyView(List<PoiInfo> poiInfos) {
        if (poiInfos!=null && poiInfos.size()>0)
            mSuggestPoiInfoList.addAll(0, poiInfos);
        stationQuerySuggestAdapter.notifyDataSetChanged();
    }

    /**
     * 清空查询建议RecyView
     */
    public void clearSuggestRecyView() {
        mSuggestPoiInfoList.clear();
        stationQuerySuggestAdapter.notifyDataSetChanged();
    }

    /**
     * 更新站点查询历史RecyView
     */
    private void updateStationInfoHistoryRecyView() {
        mStationInfoHistoryList.clear();
        mStationInfoHistoryList.addAll(BRTQCache.getInstance().getStationInfoHistoryList());
        sortStationInfoHistory();
        stationInfoHistoryAdapter.notifyDataSetChanged();
        setHistoryClearBtnVisibility();
    }

    /**
     * 将展示的站点历史按照时间进行排序
     */
    public void sortStationInfoHistory() {
        Collections.sort(mStationInfoHistoryList, new Comparator<StationInfo>() {
            public int compare(StationInfo o1, StationInfo o2) {
                return o2.getTime().compareTo(o1.getTime());
            }
        });
    }

    /**
     * 将展示的收藏站点按照时间进行排序
     */
    public void sortStationInfoCollect() {
        Collections.sort(mStationInfoCollectList, new Comparator<StationInfoCollect>() {
            public int compare(StationInfoCollect o1, StationInfoCollect o2) {
                return o2.getTime().compareTo(o1.getTime());
            }
        });
    }

    /**
     * 设置“清除站点查询历史”按钮是否可见
     */
    public void setHistoryClearBtnVisibility() {
        if (mStationInfoHistoryList.size() > 0) mHistoryClearBtn.setVisibility(View.VISIBLE);
        else mHistoryClearBtn.setVisibility(View.GONE);
    }

    /**
     * 更新附近站点RecyView
     *
     * @param poiInfos
     * @param latLng
     */
    public void updateNearbyRecyView(List<PoiInfo> poiInfos, LatLng latLng) {
        mNearbyPoiInfoList.clear();
        mNearbyPoiInfoList.addAll(0, poiInfos);
        stationQueryNearByAdapter.updateDistance(latLng);
    }

    /**
     * 更新站点收藏RecyView
     */
    private void updateStationInfoCollectRecyView() {
        User user = BmobUser.getCurrentUser(User.class);
        if (user != null) {
            mCollectRecyclerView.setVisibility(View.VISIBLE);
            mCollectText.setVisibility(View.GONE);
            mStationInfoCollectList.clear();
            mStationInfoCollectList.addAll(BRTQCache.getInstance().getStationInfoCollectList());
            sortStationInfoCollect();
            stationInfoCollectAdapter.notifyDataSetChanged();
        }else{
            mCollectRecyclerView.setVisibility(View.GONE);
            mCollectText.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 切换 查询建议, 历史记录，附近站点，收藏站点 的recyclerView
     *
     * @param tag 0 显示查询建议, 1 显示历史记录， 2 显示附近站点， 3 显示收藏站点
     */
    public void changeNowRecyView(int tag) {
        for (int i = 0; i < mButtonList.size(); i++) {
            if (tag == 0) mSuggestSwipeRefreshLayout.setVisibility(View.VISIBLE);
            else mSuggestSwipeRefreshLayout.setVisibility(View.GONE);
            if (tag == 1) mHistoryLayout.setVisibility(View.VISIBLE);
            else mHistoryLayout.setVisibility(View.GONE);
            if (tag == 2) mNearByRecyclerView.setVisibility(View.VISIBLE);
            else  mNearByRecyclerView.setVisibility(View.GONE);
            if (tag == 3) mCollectLayout.setVisibility(View.VISIBLE);
            else  mCollectLayout.setVisibility(View.GONE);
            if (i == tag) {
                mButtonList.get(i).setBackgroundResource(R.drawable.shape_btn_corners_5dp);
//                recyclerViewList.get(i).setVisibility(View.VISIBLE);
            } else {
                mButtonList.get(i).setBackgroundColor(Color.TRANSPARENT);
//                recyclerViewList.get(i).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onDestroy() {
        mPoiSearch.destroy();
        super.onDestroy();
    }

}